
"""
Converts a function in python  to a fortran procedure
"""
from numpy.f2py import f2py2e
import sys

class FCode:
    '''
    Acts as a repository for fortran converted functions.
    '''
    def __init__(self):
        self.code = {}
    def fortranize(self,func):
        '''
        decorator to convert the function to fortran
        '''
        if func.__name__ not in self.code:
            functrans = self.translate(func)
            self.code[func.__name__] = functrans
        def newFunc(*args,**kwargs):
            return functrans(*args,**kwargs)
        newFunc.__name__ = func.__name__
        newFunc.__doc__ = func.__doc__
        newFunc.__dict__.update(func.__dict__)
        return newFunc

    def translate(self,func):
        if sys.platform == 'linux2':
            f2py_args = "--fcompiler='Gnu'"
        elif sys.platform =='nt':
            pass
        # TODO: implement code generation
        r = f2py2e.compile(source,modulename = 'functrans', extra_args=f2py_args,verbose=True,
                           sourcecodefile=func.__name__+'.f')
        if r:
            print "Compilation failed"
            sys.exit(1)
        import functrans
        return functrans
